<template>
  <CDialog
    class="reduction-dialog"
    title="碳资产交易登记"
    v-model:visible="dialogVisible"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
    :loading="loading"
    size="default"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-position="top">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="排放单位" prop="assetNo">
            <el-tree-select
              v-model="formData.assetNo"
              :data="dischargeUnitOptions"
              check-strictly
              filterable
              default-expand-all
              :props="{
                label: 'assetDepartment',
                children: 'subAccountList'
              }"
              placeholder="请选择"
              :suffix-icon="SelectIcon"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="交易方向" prop="transactionType">
            <el-radio-group
              v-model="formData.transactionType"
              name="transactionType"
              @change="handleChangeTransactionType"
            >
              <el-radio
                v-for="item in TradingDirectionFilterOption"
                :key="item.value"
                :label="item.value"
              >
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资产类别" prop="assetType">
            <el-select
              v-model="formData.assetType"
              placeholder="请选择"
              :suffix-icon="SelectIcon"
              :disabled="assetTypeDisabled"
            >
              <el-option
                v-for="item in AssetsClassOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="交易日期" prop="transactionDate">
            <el-date-picker
              class="date-time__picker"
              v-model="formData.transactionDate"
              type="date"
              :clearable="false"
              placeholder="请选择"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              style="width: 100%"
              :prefix-icon="DateTimeIcon"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="交易量" prop="transactionNumber">
            <el-input
              v-model="formData.transactionNumber"
              :min="0"
              :max="999999999"
              v-positive-only:6
              type="number"
              placeholder="请输入"
              @input="hanleInput"
            >
              <template #suffix> tCO₂ </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="可用量" prop="availableQuantity">
            <template #label>
              <div class="g-flex-between-center available-quantity__label">
                <span>可用量</span>
                <template v-if="!hideYear">
                  <div class="label-right g-flex-end-center" @click="handleOpenDateYear">
                    <span
                      >年份{{
                        formData.transactionYear ? `-${formData.transactionYear}` : ''
                      }}</span
                    >
                    <CIcon
                      type="c-xian-xia"
                      :class="['arrow-icon', { 'rotate-icon': dateYearVisible }]"
                    ></CIcon>
                  </div>
                  <el-form-item class="form-item__year" label="" prop="transactionYear">
                    <el-date-picker
                      ref="transactionYearRef"
                      class="date-time__picker"
                      v-model="formData.transactionYear"
                      type="year"
                      :clearable="false"
                      placeholder="请选择"
                      value-format="YYYY"
                      format="YYYY"
                      style="width: 100%"
                      :prefix-icon="DateTimeIcon"
                      @visible-change="handleVisibleChange"
                    />
                  </el-form-item>
                </template>
              </div>
            </template>
            <el-input
              v-model="formData.availableQuantity"
              :min="0"
              :max="999999999"
              v-positive-only:6
              type="number"
              placeholder=""
              disabled
            >
              <template #suffix> tCO₂ </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="交易单价" prop="transactionPrice">
            <el-input
              v-model="formData.transactionPrice"
              :min="0"
              :max="999999999"
              v-positive-only:6
              type="number"
              placeholder="请输入"
              @input="hanleInput"
            >
              <template #suffix> 元 </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="交易手续费" prop="transactionCost">
            <el-input
              v-model="formData.transactionCost"
              :min="0"
              :max="999999999"
              v-positive-only:6
              type="number"
              placeholder="请输入"
              @input="hanleInput"
            >
              <template #suffix> 元 </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="交易总金额" prop="transactionTotalAmount">
            <el-input
              v-model="formData.transactionTotalAmount"
              :min="0"
              :max="999999999"
              v-positive-only:6
              type="number"
              placeholder="请输入"
            >
              <template #suffix> 元 </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" maxLength="20" placeholder="请输入"> </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </CDialog>
</template>
<script lang="ts">
import Decimal from 'decimal.js';
export default {
  name: 'CarbonAssetRegisterDialog'
};
</script>
<script lang="ts" setup>
import {
  defineProps,
  withDefaults,
  defineEmits,
  computed,
  ref,
  reactive,
  watch,
  defineComponent,
  h,
  watchEffect
} from 'vue';
import { CDialog } from '@/components/CDialog';
import { useMessage } from '@/hooks/useMessage';
import { TradingDirectionOption, AssetsClassOption } from '@/constants/enum';
import { rules } from './rules';
import { createCarbonTransaction, getAccessQuotaByNoAndYear } from '@/apis/taa/asset/account';
import { GIcon } from '@/components/GIcon/index';
import { getAccountTree } from '@/apis/taa/asset/account';
import type { GetAccountListResult } from '@/apis/taa/asset/model/accountModel';

// 下拉图标
const SelectIcon = defineComponent({
  setup() {
    return () => h(GIcon, { type: 'c-xian-xia', style: 'font-size: 16px' });
  }
});

// 时间图标
const DateTimeIcon = defineComponent({
  setup() {
    return () => h(GIcon, { type: 'c-xian-riqi', style: 'font-size: 14px' });
  }
});

// 交易方向options过滤
const TradingDirectionFilterOption = computed(() => {
  return TradingDirectionOption.filter(item => item.value !== 'PAYMENT_PERFORMANCE');
});

interface CreateTargetDialogProps {
  visible: boolean;
}
const props = withDefaults(defineProps<CreateTargetDialogProps>(), {
  visible: false
});
const emit = defineEmits(['update:visible', 'refresh']);

const { createMessage } = useMessage();

const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emit('update:visible', val);
  }
});
watch(
  () => dialogVisible.value,
  visible => {
    if (!visible) {
      // 关闭时清空数据
      handleClear();
    } else {
      // 打开时初始化新数据
      initVisible();
    }
  }
);

const formRules = computed<any>(() => {
  return rules({ validateTransactionNumber });
});

function validateTransactionNumber(rule: any, value: any, callback: any) {
  console.log(rule, 'any', value, 'any', callback, 'any');
  if (value === '') {
    callback(new Error('必填项'));
  }
  if (
    formData.transactionType === 'SELL_QUOTA' &&
    Number(formData.transactionNumber) > formData.availableQuantity
  ) {
    callback(new Error('交易量不能大于可用量'));
  }
  callback();
}

const formRef = ref();
const loading = ref(false);
const transactionYearRef = ref();
const hideYear = ref(false);

const formData = reactive({
  assetNo: '',
  transactionType: '',
  assetType: '',
  transactionDate: '',
  transactionNumber: '',
  availableQuantity: 0,
  transactionYear: new Date().getFullYear().toString(),
  transactionPrice: '',
  transactionCost: '',
  transactionTotalAmount: '',
  remark: ''
});

watchEffect(() => {
  if (formData.assetNo && formData.assetType && formData.transactionYear) {
    console.log('查询可用额度');
    getAssetBalanceFn();
  }
});

watchEffect(() => {
  if (['CARBON_REDUCTION', 'CARBON_INCLUSIVE'].includes(formData.assetType)) {
    hideYear.value = true;
  } else {
    hideYear.value = false;
  }
});

interface CustomGetAccountListResult extends GetAccountListResult {
  value: string;
}
const dischargeUnitOptions = ref<CustomGetAccountListResult[]>([]);
async function getDischargeUnitOptions() {
  try {
    const data = await getAccountTree();
    const dfs = (data: GetAccountListResult[]) => {
      if (!data?.length) return;
      for (let i = 0; i < data.length; i++) {
        const item = data[i];
        Object.assign(item, {
          value: item.assetNo
        });
        if (item?.subAccountList?.length) {
          dfs(item.subAccountList);
        }
      }
    };
    dfs(data);
    dischargeUnitOptions.value = data as CustomGetAccountListResult[];
  } catch (error) {
    console.log(error, 'error');
    dischargeUnitOptions.value = [];
  }
}

const assetTypeDisabled = ref(false);
function handleChangeTransactionType(value: string) {
  if (value === 'QUOTA_ALLOCATION') {
    formData.assetType = 'CARBON_QUOTA';
    assetTypeDisabled.value = true;
  } else {
    assetTypeDisabled.value = false;
  }
}

function handleOpenDateYear() {
  console.log(transactionYearRef.value, 'transactionYearRef.value---');
  transactionYearRef.value.handleOpen();
}

const dateYearVisible = ref(false);
function handleVisibleChange(visibility: boolean) {
  console.log(visibility, 'visibility--');
  dateYearVisible.value = visibility;
}

async function getAssetBalanceFn() {
  try {
    const data = await getAccessQuotaByNoAndYear(
      formData.assetNo,
      formData.assetType,
      formData.transactionYear
    );
    formData.availableQuantity = data || 0;
    console.log(data, 'aaaaaa');
  } catch (error) {
    loading.value = false;
  }
}

function hanleInput() {
  // 数量
  const transactionNumber = new Decimal(formData.transactionNumber || 0);
  // 单价
  const transactionPrice = new Decimal(formData.transactionPrice || 0);
  // 手续费
  const transactionCost = new Decimal(formData.transactionCost || 0);
  // 总价
  formData.transactionTotalAmount = transactionNumber
    .times(transactionPrice)
    .plus(transactionCost)
    .toString();
}

// 提交按钮
function handleConfirm() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      submitTaskReq();
    }
  });
}

// 请求接口
async function submitTaskReq() {
  try {
    loading.value = true;
    const params: any = formData;
    await createCarbonTransaction(params);
    createMessage.success('碳交易登记成功');
    dialogVisible.value = false;
    loading.value = false;
    emit('refresh');
  } catch (error) {
    loading.value = false;
  }
}

// 关闭时清空数据
function handleClear() {
  loading.value = false;
  formRef.value?.resetFields();
}

// 打开时初始化
async function initVisible() {
  // 获取工厂下拉选项
  getDischargeUnitOptions();
  handleClear();
}
</script>
<style lang="scss" scoped>
.available-quantity__label {
  margin-right: -12px;
  position: relative;
}
.label-right {
  color: #308bf2;
  cursor: pointer;
  position: absolute;
  top: 50%;
  right: 0;
  z-index: 999;
  transform: translateY(-50%);
  .arrow-icon {
    font-size: 20px;
    transition: transform 0.3s;
  }
  .rotate-icon {
    transform: rotateX(180deg);
  }
}
.form-item__year {
  width: 48px;
  height: 22px;
  opacity: 0;
}
</style>
<style lang="scss">
.reduction-dialog {
  .el-input {
    .el-input__wrapper {
      padding-right: 10px !important;
    }
  }

  .date-time__picker {
    .el-input__wrapper {
      .el-input__prefix {
        order: 3;
        .el-input__prefix-inner > :last-child {
          margin-right: unset;
        }
      }
    }
  }
}
</style>
